package com.myapp.actions.visit;

import com.myweb.WebAction;
import com.myweb.WebException;
import com.myweb.WebRequest;
import com.myweb.WebResponse;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

public class ListVisits implements WebAction {

  private String query;
  private int start;
  private int length;

  @Override
  public void prepare(WebRequest req) throws WebException {
    query = req.getString("query");
    start = req.getInteger("start");
    length = req.getInteger("length");
  }

 @Override
    public EntityManager process(WebRequest req, WebResponse res, EntityManager em) throws Exception {
    Query q = em.createQuery("SELECT v FROM Visit v WHERE v.deleted = false AND (v.client.firstName LIKE :f "
            + "OR v.client.middleName LIKE :m OR v.client.lastName LIKE :l OR v.reasonForConsult LIKE :r)");
    q.setFirstResult(start);
    q.setMaxResults(length);
    q.setParameter("f", "%" + query + "%");
    q.setParameter("m", "%" + query + "%");
    q.setParameter("l", "%" + query + "%");
    q.setParameter("r", "%" + query + "%");
    res.setResult(q.getResultList());
    return em;
  }
}
